/**
 * Created by seikann on 2017-11-24.
 */
import axios from 'axios'

export default {
  install(Vue, options) {

// api:接口地址, param:接口入参, thisVue:当前的vue对象(为引用iview的message组件)
//     res.data.code : -1 = 错误,0 = 正确结果, 1 = 未登录
    Vue.prototype.$post = function (thisVue, api, params) {
      let PromiseHttp = new Promise(function (resolve, reject) {
        axios.post(api, params)
          .then(function (res) {
            switch (res.data.code) {
              case '1':
                thisVue.$Message.error(res.data.message);
                window.setTimeout(function () {
                  if (thisVue && !thisVue._isDestroyed) { //_isDestroyed 组件是否被销毁
                    thisVue.$router.push({
                      path: '/login'
                    })
                  }
                }, 1000);
                break;
              case '0':
                resolve(res.data);
                break;
              default:
                thisVue.$Message.error(res.data.message);
                break;
            }
          })
          .catch(function (err) {
            console.log(err)
          });
      });
      return PromiseHttp;
    };

    Vue.prototype.$get = function (thisVue, api, params) {
      let PromiseHttp = new Promise(function (resolve, reject) {
        axios.get(api, {params: params})
          .then(function (res) {
            switch (res.data.code) {
              case '1':
                thisVue.$Message.error(res.data.message);
                window.setTimeout(function () {
                  if (thisVue && !thisVue._isDestroyed) { //_isDestroyed 组件是否被销毁
                    thisVue.$router.push({
                      path: '/login'
                    })
                  }
                }, 1000);
                break;
              case '-1':
                thisVue.$Message.error(res.data.message);
                break;
              default:
                resolve(res.data);
                break;
            }
          })
          .catch(function (err) {
            console.log(err)
          })
      });
      return PromiseHttp;
    };
  }
}
